package cn.e4j.modular.system.service.impl;

import cn.e4j.core.dto.impl.Dto;
import cn.e4j.modular.system.entity.SysMail;
import cn.e4j.modular.system.mapper.SysMailMapper;
import cn.e4j.modular.system.model.EmailProperties;
import cn.e4j.modular.system.service.SysMailService;
import com.baomidou.dynamic.datasource.toolkit.CryptoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.URLDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * <p> 系统邮件参数配置表 服务实现类 </p>
 * @author wenchuan.li
 * @since 2018-12-13
 */
@Service
public class SysMailServiceImpl extends ServiceImpl<SysMailMapper, SysMail> implements SysMailService {

    private JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

    @Override
    public List<Map<String, Object>> getMailList(Page<Object> page, Dto inDto) {
        return this.baseMapper.getMailList(page, inDto);
    }

    @Override
    public void add(SysMail mail) {
        mail.insert();
    }

    @Override
    public void edit(SysMail mail) {
        QueryWrapper<SysMail> mailTQueryWrapper = new QueryWrapper<>();
        mailTQueryWrapper.eq("ID",mail.getID());
        SysMail oldMail = this.baseMapper.selectOne(mailTQueryWrapper);

        if(!oldMail.getMAIL_PAW().equals(mail.getMAIL_PAW())) {
            try {
                mail.setMAIL_PAW(CryptoUtils.encrypt(mail.getMAIL_PAW()));
            } catch (Exception e) {
                throw new RuntimeException("对邮箱密码加密失败");
            }
        }
        mail.updateById();
    }


    @Override
    public void delete(SysMail mail) {
        String id = mail.getID();
        mail.deleteById(id);
    }

    @Override
    public void deleteBatch(List<SysMail> mailList) {
        List<String> idList = new ArrayList<>();
        for (SysMail mail : mailList) {
            idList.add(mail.getID());
        }
        this.removeByIds(idList);
    }

    // 邮件属性设置
    public void setEmailProperties(EmailProperties properties) {
        javaMailSender.setHost(properties.getHost());
        javaMailSender.setUsername(properties.getUsername());
        javaMailSender.setPassword(properties.getPwd());
    }

    /**
     * 发送邮件
     * Springboot集成 javaMail 写法 （当前版本使用）
     * @throws MessagingException
     */
    @Async
    public void sendEmailWithAttach(EmailProperties properties) throws MessagingException {
        setEmailProperties(properties);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 第二个参数是 true ，表明这个消息是 multipart类型的
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(properties.getFrom());
        mimeMessageHelper.setTo(properties.getTo());
        mimeMessageHelper.setSubject(properties.getSubject());
        mimeMessageHelper.setText(properties.getText());

//        如果有附件的话就添加附件
        if(StringUtils.isNotEmpty(properties.getAttachUrl())) {
            String[] attachUrls = properties.getAttachUrl().split(",");
            String[] attachNames = properties.getAttachName().split(",");
            for(int i = 0; i < attachUrls.length; i++) {
                // 使用URL构建DataSource
                URL url = null;
                try {
                    // 测试图片发送
                    url = new URL(attachUrls[i]);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                //添加附件,第一个参数表示添加到 Email 中附件的名称，第二个参数是图片资源
                mimeMessageHelper.addAttachment(attachNames[i], new URLDataSource(url));
            }
        }
        javaMailSender.send(mimeMessage);
    }

    @Override
    public Boolean existedTheParams(String id) {
        QueryWrapper<SysMail> mailTQueryWrapper = new QueryWrapper<>();
        mailTQueryWrapper.eq("MAILUD001","Y");
        List<SysMail> resultList = this.baseMapper.selectList(mailTQueryWrapper);
        return resultList.size() > 0 && !resultList.get(0).getID().equals(id);
    }

    /**
     * 发送邮件
     * 单纯使用javaMail API写法（老版本写法,本系统暂未使用）
     * @throws MessagingException
     */
    public void sendstartEmail(String[] receiver, String theme) {
        /*邮件服务器*/
        String send_mail_adress = "dwm6.digiwin.com";
        /*发件邮箱账号*/
        String send_mail_userName = "your username@digiwin.com";
        /*发件邮箱密码*/
        String send_mail_passwd = "your password";
        final Properties props = new Properties();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                /*表示SMTP发送邮件，需要进行身份验证*/
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.host", send_mail_adress);/*发件人帐号*/
                props.put("mail.user", send_mail_userName);
                props.put("mail.password", send_mail_passwd);/*构建授权信息，用于进行SMTP身份验证*/

                Authenticator authenticator = new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        String userName = props.getProperty("mail.user");
                        String password = props.getProperty("mail.password");
                        return new PasswordAuthentication(userName, password);
                    }
                };
                /*使用环境属性和授权信息，创建邮件会话*/
                Session mailSession = Session.getInstance(props, authenticator);/*创建邮件消息*/
                MimeMessage message = new MimeMessage(mailSession);
                InternetAddress from = null;
                try {
                    /*设置发件人*/
                    from = new InternetAddress(props.getProperty("mail.user"));
                    message.setFrom(from);

                    /*设置收件人*/
                    Address[] addresses = new Address[receiver.length];
                    for (int i = 0, j = receiver.length; i < j; i++) {
                        addresses[i] = new InternetAddress(receiver[i]);
                    }
                    /*receiver为收件人邮箱！*/
                    message.setRecipients(Message.RecipientType.TO, addresses);

                    /* 设置抄送
                    InternetAddress cc = new InternetAddress("xxxxx@digiwin.biz");
                    message.setRecipient(Message.RecipientType.CC, cc);
                    */

                    /*设置邮件标题*/
                    String subject = theme + ":启用通知";
                    message.setSubject("【设备售后维修保养[MMR]平台】" + subject);

                    //设置邮件的正文
                    MimeBodyPart text = new MimeBodyPart();
                    // setContent(“邮件的正文内容”,”设置邮件内容的编码方式”)
                    String cd = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
                            + "<html xmlns='http://www.w3.org/1999/xhtml'>"
                            + "<head>"
                            + "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
                            + "<title>定时任务通知</title>"
                            + "</head>"
                            + "<body>"
                            + "<p>您有一条来自"+"【设备售后维修保养[MMR]平台】"+"的定时任务信息："+"【"+subject+"】"+"已经停用,请及时查看！</p>"
                            + "<img src=\"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRdW_EinCxCAZsaTCNXTtYm7NwOs8Wqd_IM7qV8eC_kRj7He61b&s\" />"
                            +"</body></html>";
                    text.setContent(cd,
                            "text/html;charset=gb2312");

                    // 创建附件
                    MimeBodyPart attach = new MimeBodyPart();
                    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                    URL url = new URL("http://fx.digiwin.com:9017/wissun-smfile/5d9d8a04-3938-41d4-84e7-96f628b2eb49.jpg");
                    DataHandler dh1 = new DataHandler(new URLDataSource(url));
                    attach.setDataHandler(dh1);

                    MimeMultipart mm = new MimeMultipart();
                    mm.addBodyPart(text);
                    mm.addBodyPart(attach);

                    message.setContent(mm);

                    /*发送邮件*/
                    Transport.send(message);

                    /*添加邮件日志
                    for (int i=0,j=receiver.length;i<j;i++){
                        String mail_receiverName = findReceiver(receiver[i]);
                        addMaillog(mail_receiverName,send_mail_userName,receiver[i],subject);
                    }*/
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    public static void main(String[] args) throws Exception {
//        EmailProperties properties = new EmailProperties();
//        properties.setHost("dwm6.digiwin.com");
//        properties.setUsername("ganjia@digiwin.com");
//        properties.setPwd("Digiwin0324");
//        properties.setFrom("ganjia@digiwin.com");
//        properties.setTo("liuweiz@digiwin.com");
//        properties.setSubject("客户问题提报");
//        properties.setText("发送邮件测试");
//        properties.setAttachUrl("http://localhost:8080/wissun-smfile/3d7b08e3-a979-43dc-a75e-6bbb07b02960.jpg");
//        properties.setAttachName("问题截图");
//        new SysMailServiceImpl().sendEmailWithAttach(properties);
//        System.out.println(CryptoUtils.decrypt("Pq14IJU143BYSXDUlfOL7OR/CO6nJAtTf9yUUT+rbXkAirmI+LuC3f1LaepY53SyFTGmODRejPMvlEKka9CHng=="));
    }
}
